package com.connector.server.server.listener;

import org.slf4j.LoggerFactory;
import com.connector.base.connection.Connection;
import com.connector.base.message.model.ErrorMessage;
import com.connector.server.util.SendMsgUtil;
import com.connector.server.jmx.JmxMessageBean;
import com.connector.base.utils.ErrorCode;
import com.connector.base.message.model.BaseMessage;
import com.google.common.base.Strings;
import com.connector.base.connection.channel.SocketChannel;
import com.connector.base.connection.channel.SocketIoSocketChannel;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.connector.base.connection.ConnectionRegistry;
import org.slf4j.Logger;
import com.connector.base.message.model.ChatMessage;
import com.corundumstudio.socketio.listener.DataListener;

public class SocketIoChatListener implements DataListener<ChatMessage>
{
    private static final Logger log;
    public static final String SOCKETIO_EVENT_CHAT = "message";
    private final ConnectionRegistry connectionRegistry;
    
    public SocketIoChatListener(final ConnectionRegistry connectionRegistry) {
        this.connectionRegistry = connectionRegistry;
    }
    
    public void onData(final SocketIOClient socketIOClient, final ChatMessage chatMessage, final AckRequest ackRequest) {
        final Connection connection = this.connectionRegistry.get((SocketChannel)new SocketIoSocketChannel(socketIOClient));
        if (Strings.isNullOrEmpty(chatMessage.getDeviceId())) {
            BaseMessage.buildErrorResponse(connection).setErrorCode(ErrorCode.INVALID_DEVICE).buildResult("Param invalid", "没有找到设备标识！").close();
            return;
        }
        try {
            BaseMessage.buildSuccessResponse(connection).send("message");
            chatMessage.setPcOrApp(Boolean.valueOf(false));
            SendMsgUtil.sendMsg(JmxMessageBean.build(chatMessage));
        }
        catch (Throwable e) {
            ErrorMessage.buildErrorResponse(connection).setErrorCode(ErrorCode.CHAT_FAILURE).buildResult(e.getMessage(), "构建响应失败！").close();
            SocketIoChatListener.log.error("构建响应失败!", e);
        }
    }
    
    static {
        log = LoggerFactory.getLogger((Class)SocketIoChatListener.class);
    }
}
